package com.gitee.wsl.ext.list

import com.gitee.wsl.ext.collection.fill


fun <T> MutableList<T>.truncate(newSize: Int) {
    check(newSize > 0) { "'newSize' must be >= 0: $newSize" }
    if (size <= newSize) return
    subList(newSize, size).clear()
}

/**
 * @return a list of [size]. New items are created with [create] if there are too few.
 */
fun <T> List<T>.exactSize(size: Int, create: () -> T): List<T>
{
    return when
    {
        this.size == size -> this

        // Too many elements, get the exact amount needed.
        this.size > size -> this.take(size)

        // Too few elements, create new ones.
        else -> this.fill(size, create).toList()
    }
}

fun <T> ArrayList<ArrayList<T>>.ensureSize(size: Int) {
    if (this.size >= size) return
    repeat(size - this.size) {
        add(ArrayList())
    }
}